package com.jeehentor.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeehentor.common.exception.HentorException;
import com.jeehentor.dto.DepartDTO;
import com.jeehentor.dto.IdsRequestDTO;
import com.jeehentor.dto.QueryDepartDTO;
import com.jeehentor.entity.SysDepart;
import com.jeehentor.system.mapper.SysDepartMapper;
import com.jeehentor.system.service.ISysDepartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构表 服务实现类
 * </p>
 *
 * @author wzd
 * @since 2024-04-17
 */
@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysDepartService {

    @Override
    public void addDepart(DepartDTO departDTO) {
        LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDepartLambdaQueryWrapper
                .eq(SysDepart::getOrgCode, departDTO.getOrgCode());
        SysDepart sysDepart = this.getOne(sysDepartLambdaQueryWrapper);
        if (sysDepart != null) {
            throw new HentorException("部门编码已存在");
        }
        SysDepart depart = new SysDepart();
        BeanUtils.copyProperties(departDTO, depart);
        save(depart);
    }

    @Override
    public Page<DepartDTO> selectDepart(QueryDepartDTO queryDepartDTO) {
        LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据部门名称模糊查询
        sysDepartLambdaQueryWrapper.like(StringUtils.isNotBlank(queryDepartDTO.getDepartName()),SysDepart::getDepartName, queryDepartDTO.getDepartName());
        // 根据部门名称空查询
        sysDepartLambdaQueryWrapper.isNull(StringUtils.isBlank(queryDepartDTO.getDepartName()),SysDepart::getParentId);
        // 分页查询部门信息
        Page<SysDepart> sysDepartPage = page(queryDepartDTO.getPage(), sysDepartLambdaQueryWrapper);
        Page<DepartDTO> departModelPage = new Page<>();
        // 设置分页总记录数
        departModelPage.setTotal(sysDepartPage.getTotal());
        // 设置分页显示记录数
        departModelPage.setSize(sysDepartPage.getSize());
        // 设置分页当前页码
        departModelPage.setCurrent(sysDepartPage.getCurrent());
        // 设置分页总页码
        departModelPage.setPages(sysDepartPage.getPages());
        // 将查询到的部门信息转换为DepartDTO类型
        List<DepartDTO> departDTOS = sysDepartPage.getRecords().stream()
                .map(sysDepart -> {
                    DepartDTO departDTO = new DepartDTO(); // 假设DepartModel有无参构造函数
                    BeanUtils.copyProperties(sysDepart, departDTO); // 将SysDepart的属性复制到DepartModel
                    return departDTO;
                })
                .collect(Collectors.toList());
        // 构建部门树
        ArrayList<String> ids = new ArrayList<>();
        buildDepartTree(departDTOS,ids);
        // 去除部门树中的节点
        departDTOS.removeIf(x->ids.contains(x.getId()));
        // 设置返回结果为部门树中的节点
        departModelPage.setRecords(departDTOS);
        return departModelPage;
    }

    @Override
    public List<DepartDTO> selectList() {
        LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDepartLambdaQueryWrapper.isNull(SysDepart::getParentId);
        List<SysDepart> list = list(sysDepartLambdaQueryWrapper);
        List<DepartDTO> modelList = list.stream().map(x -> {
            DepartDTO departDTO = new DepartDTO(); // 假设DepartModel有无参构造函数
            BeanUtils.copyProperties(x, departDTO); // 将SysDepart的属性复制到DepartModel
            return departDTO;
        }).toList();
        buildDepartTree(modelList,new ArrayList<>());
        return modelList;
    }

    @Override
    public void updateDepart(DepartDTO departDTO) {
        LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDepartLambdaQueryWrapper.eq(SysDepart::getOrgCode, departDTO.getOrgCode());
        SysDepart depart = getOne(sysDepartLambdaQueryWrapper);
        if(depart != null && !depart.getId().equals(departDTO.getId())){
            throw new HentorException("组织机构代码已存在");
        }
        updateById(departDTO);
    }

    @Override
    public void deleteDepart(IdsRequestDTO ids) {
        ids.getIds().forEach(x -> {
            LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysDepartLambdaQueryWrapper.eq(SysDepart::getParentId, x);
            List<SysDepart> list = list(sysDepartLambdaQueryWrapper);
            if (list.size() > 0) {
                throw new HentorException("存在下级部门，无法删除");
            }else {
                removeById(x);
            }
        });
    }

    private void buildDepartTree(List<DepartDTO> departDTOS,List<String> ids){
        for (DepartDTO departDTO : departDTOS) {
            LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysDepartLambdaQueryWrapper.eq(SysDepart::getParentId, departDTO.getId());
            List<SysDepart> sysDeparts = list(sysDepartLambdaQueryWrapper);
            if(CollectionUtil.isNotEmpty(sysDeparts)){
                List<DepartDTO> collect = sysDeparts.stream().map(x -> {
                    ids.add(x.getId());
                    DepartDTO model = new DepartDTO();
                    BeanUtils.copyProperties(x, model);
                    return model;
                }).collect(Collectors.toList());
                departDTO.setChildren(collect);
                buildDepartTree(collect,ids);
            }
        }
    }
}
